<!--
 * @Description: 检测管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="70"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        :row-class-name="tableRowClassName"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="detectionTypeName" label="检测类型" />
        <el-table-column prop="batchName" label="批次名称" min-width="120" />
        <el-table-column prop="lesseeNo" label="种植户名称" min-width="120">
          <template slot-scope="scope">{{ tenantObj[scope.row.lesseeNo] || '' }}</template>
        </el-table-column>
        <el-table-column prop="number" label="抽检数量" min-width="100">
          <template
            slot-scope="scope"
          >{{ scope.row.number }} {{ scope.row.unitName }}</template>
        </el-table-column>
        <el-table-column
          prop="detectionTime"
          :formatter="dateFormat"
          label="检测时间"
          min-width="90"
        />
        <el-table-column prop="detectionPictureId" label="检测报告" width="90">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.detectionTypeNo"
              type="text"
              size="mini"
              @click="pic(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-if="scope.row.detectionNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(70, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(70, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '检测信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="检测类型:" prop="detectionTypeNo" class="w100p">
            <el-select v-model="formData.detectionTypeNo" clearable filterable>
              <el-option
                v-for="item in treeDatas"
                :key="item.detectionTypeNo"
                :label="item.detectionTypeName"
                :value="item.detectionTypeNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="批次名称:" prop="productionBatchNo" class="w100p">
            <el-select
              v-model="formData.productionBatchNo"
              filterable
              clearable
              @change="warehouseBatch"
            >
              <el-option
                v-for="item in warehouseBatchArrAll"
                :key="item.batchNo"
                :label="item.batchName"
                :value="item.batchNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="抽检数量:" prop="number" style="width: 50%">
            <el-input
              v-model="formData.number"
              placeholder="请输入抽检数量"
              clearable
            />
          </el-form-item>
          <el-form-item label="单位:" prop="unitNo" style="width: 50%">
            <el-select
              v-model="formData.unitNo"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="item in UnitData"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检测时间:" prop="detectionTime" class="w100p">
            <el-date-picker
              v-model="formData.detectionTime"
              type="datetime"
              value-format="timestamp"
              placeholder="请选择检测时间"
              clearable
            />
          </el-form-item>
          <el-form-item label="检测报告:" prop="detectionPictureId" class="w100p">
            <ele-upload-image
              v-model="image"
              multiple
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :file-size="10"
              :action="ImageUrl()"
            />
            <!--                          :httpRequest="beforeUpload"
            -->
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog
        class="dialog"
        title="查看检测报告"
        :visible.sync="dialogFormsVisible"
      >
        <img :src="image" />
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
import DetectionManage from "@/api/digital-operation/detection-manage-ment/detection-manage/index";
import TenantManage from "@/api/digital-operation/tenant-manage/tenant-info";
import detectionTypeManage from "@/api/digital-operation/detection-manage-ment/detection-type-manage/index";
import unitInfoManage from "@/api/basic-info-manage/unit-manage/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
export default {
  name: "DetectionManage",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
    StartTimeEndTimeSelectionBox,
    // uploadimages
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '检测类型',
          prop: 'detectionTypeNo',
          type: 'select',
          options: [], // treeDatas
          optionKey: { label: 'detectionTypeName', value: 'detectionTypeNo' },
        }, {
          label: '批次名称',
          prop: 'productionBatchNo',
          type: 'select',
          options: [], // warehouseBatchArrAll
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '种植户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // tenantData
          optionKey: { label: 'lesseeName', value: 'lesseeNo' },
        }, {
          label: '投产日期',
          prop: 'date',
          type: 'daterange',
        },
      ],
      searchlist: {},
      // 查询时间
      detectionTime: undefined,
      // 检测类型Id
      detectionTypeNo: "",
      rules: {
        detectionTypeNo: [
          { required: true, message: "请选择检测类型", trigger: "change" }
        ],
        productionBatchNo: [
          { required: true, message: "请选择批次名称", trigger: "change" }
        ],
        number: [
          { required: true, message: "请输入检测数量", trigger: "blur" }
        ],
        unitNo: [{ required: true, message: "请选择单位", trigger: "change" }],
        detectionTime: [
          { required: true, message: "请选择时间", trigger: "change" }
        ]
      },
      dialogFormsVisible: false,
      disabled: false,
      lesseeNo: "",
      treeDatas: [],
      //  选中行的数据
      detectionIdList: [],
      detectionId: "",
      warehouseBatchArrAll: [],
      productionBatchNo: "",
      tenantData: [],
      tenantObj: {},
      detectionPictureId: "",
      // lesseeNo: "",
      startTime: undefined,
      endTime: undefined,
      UnitData: [],
      dialogTitle: "",
      dialogFormVisible: false,
      files: null,
      fileName: null,
      image: null
      // detectionTypeNo: null
      // token: ""
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    // this.getTreeDataList();
    this.queryDataList();
    // this.token = sessionStorage.getItem("token");
  },
  mounted() {
    //  表格数据
    this.getTableDataList();
  },
  methods: {
    getTableDataList() {
      this.loading = false;
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          organizationNo: sessionStorage.organizationNo,
          detectionTypeNo: this.searchlist.detectionTypeNo || undefined,
          productionBatchNo: this.searchlist.productionBatchNo || undefined,
          lesseeNo: this.searchlist.lesseeNo || undefined,
          // startTime: this.startTime || undefined,
          // endTime: this.endTime || undefined,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          detectionTypeName: this.detectionTypeName || undefined
        }
      };
      DetectionManage.postDeteionNange(param).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    // // 上传图片
    ImageUrl() {
      // console.log(this.nowChanceStau)
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${this.$baseurl.webServiceUrl}v3/detection/detectionPicture/add`;
        // console.log(URL)
        return URL;
      } else {
        let URL = "#";
        // console.log(URL)
        return URL;
      }
    },
    beforeUpload(file) {
      this.files = file.file;
      const extension = file.file.name.split(".")[1] === "png";
      const extension2 = file.file.name.split(".")[1] === "jpg";
      const isLt5M = file.file.size / 1024 / 1024 < 5;
      if (!extension && !extension2) {
        this.$message.warning("上传模板只能是 png、jpg格式!");
        return;
      }
      if (!isLt5M) {
        this.$message.warning("上传模板大小不能超过 5MB!");
        return;
      }
      this.fileName = this.files.name;
      // this.image = file.file
      // const files = file.files;
      // let filename = files[files.length - 1].name; // 只有一个文件
      // const fileReader = new FileReader(); // 内置方法new FileReader()   读取文件
      // // fileReader.readAsDataURL(files[files.length - 1]);
      // fileReader.readAsBinaryString(files[files.length - 1]);
      // fileReader.addEventListener("load", () => {
      //   this.image = window.btoa(fileReader.result.toString());
      // });
      // setTimeout(() => {
      //   this.submitUpload();
      //   this.upLoading = true
      // }, 500);
      // return file; // 返回false不会自动上传
    },
    handleResponse(response, file, fileList) {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        // return this.basicUrl + query/ + this.detectionPictureId
        this.detectionPictureId = response.data;
        this.$set(this.formData, "pictureId", response.data);
        DetectionManage.getColectPicture(this.detectionPictureId).then(res => {
          // console.log(res.data)
          this.image = "data:image/png;base64," + res.data.data;
        });
        return this.image;
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    handleRemove() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        // console.log(response);
        DetectionManage.delCollectionPicture({
          detectionNoList: [this.detectionPictureId]
        }).then(res => {
          if (res.code === 1) {
            delete this.detectionPictureId;
            delete this.formData.detectionPictureId;
            // console.log(this.formData)
            this.$message.success(res.msg);
          }
        });
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    async queryDataList() {
      // 承租户获取
      const { data: Lesses } = await TenantManage.queryLessesByCondition(1);
      this.tenantData = Lesses;
      this.setOptions(this.formConfig, 'lesseeNo', Lesses)
      let tenantObj = {}
      Lesses.map(el => { tenantObj[el.lesseeNo] = el.lesseeName })
      this.tenantObj = tenantObj
      // 单位
      const { data: unitList } = await unitInfoManage.getallBasicunitlist({});
      this.UnitData = unitList;
      const { data: resp } = await DetectionManage.querybylist({simpleData: true});
      this.warehouseBatchArrAll = resp;
      this.setOptions(this.formConfig, 'productionBatchNo', resp)
      // 获取检测类型
      const {
        data: detectionType
      } = await detectionTypeManage.getTreequeryByCondition();
      // 赋值数组
      this.treeData = detectionType;
      this.treeDatas = detectionType;
      this.setOptions(this.formConfig, 'detectionTypeNo', detectionType)
    },
    warehouseBatch(e) {
      let obj = this.warehouseBatchArrAll.filter(item => item.batchNo === e);
      // console.log(obj)
      this.$set(this.formData, "lesseeNo", obj[0].lesseeNo);
    },
    pic(row) {
      if (row.pictureId !== undefined) {
        this.dialogFormsVisible = true;
      } else {
        this.$message.warning("请先添加报告图片！！！");
      }
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e;
    },
    endVal(e) {
      this.endTime = e;
    },
    // 时间
    dateFormat(row, colnum) {
      if (row.detectionTime) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 表格行index
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
      return "rows";
    },

    // add() {
    //   this.canInput = true;
    //   this.formData = {};
    //   this.openDialog('add');
    // },
    // cancel() {
    //   this.nowChanceStau = "";
    //   this.formData = {};
    //   this.closeDialog();
    // },
    handleEdit(row) {
      this.formData = JSON.parse(JSON.stringify(row));
      this.detectionPictureId = row.pictureId;
      // console.log(this.detectionPictureId, row.pictureId);
      if (this.detectionPictureId !== undefined) {
        DetectionManage.getColectPicture(this.detectionPictureId).then(res => {
          this.image = "data:image/png;base64," + res.data.data;
        });
      } else {
        this.image = "";
      }
      // this.addActive = false;
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
      // this.openDialog('edit');
      // this.$refs.formData.resetFields()
    },
    handleSelectionChange(list) {
      this.detectionIdList = [];
      this.detectionIdList = list.map(item => item.detectionNo);
      if (this.detectionIdList.length > 0) this.delActive = true;
      else this.resetActionBar();
    },
    delmessage() {
      DetectionManage.delDetectionManageInfo(this.detectionIdList).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    handleDelete(row) {
      // DetectionManage.delDetectionManageInfo([row.detectionNo]).then((res) => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   } else {
      //     this.$message.warning(res.msg || "删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          DetectionManage.delDetectionManageInfo([row.detectionNo]).then(
            res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.getTableDataList();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            }
          );
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            this.formData.detectionPictureId = this.detectionPictureId;
            // console.log(this.formData);
            DetectionManage.editDetectionManageInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.success(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            // if (this.formData.detectionId) {
            //   delete this.formData.detectionId
            // }
            // let fileFormData = new FormData();
            // fileFormData.append("code", "t_pathology_info_excel");
            // fileFormData.append("description", "excel上传测试");
            // filename是键，file是值，就是要传的文件
            // fileFormData.append('file', this.files, this.fileName);
            // fileFormData.append('detectionTypeNo', this.formData.detectionTypeNo);
            // fileFormData.append('productionBatchNo', this.formData.productionBatchNo);
            // fileFormData.append('number', this.formData.number);
            // fileFormData.append('unitNo', this.formData.unitNo);
            // fileFormData.append('detectionTime', this.formData.detectionTime);
            // fileFormData.append('organizationNo', sessionStorage.organizationNo);
            // fileFormData.append('organizationNo', this.formData.organizationNo);
            this.treeDatas.forEach(item => {
              if (item.detectionTypeNo === this.formData.detectionTypeNo) {
                this.$set(
                  this.formData,
                  "detectionTypeId",
                  item.detectionTypeId
                );
              }
            });
            this.formData.organizationNo = sessionStorage.organizationNo;
            // this.formData.file = fileFormData
            DetectionManage.addDetectionManageInfo(this.formData).then(res => {
              // console.log(res);
              // console.log(this.formData);
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.success(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
        // this.$refs[formData].resetFields()
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style lang="scss" scoped>
.sort-box {
  display: inline-block;
  // width: 60px;
  transform: rotateY(180deg);
  .sort {
    padding: 0 5px;
    transform: rotate(-90deg);
  }
}
::v-deep .el-upload--picture-card {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #6ecae3;
}
::v-deep .el-upload--picture-card {
  position: relative;
}
::v-deep .el-upload--picture-card .el-icon-plus {
  font-size: 34px;
  color: #6ecae3;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
::v-deep .el-dialog__body {
  height: 90%;
  text-align: center;
  img {
    width: 100%;
  }
}
::v-deep .el-upload__tip {
  display: none;
}
</style>
